#!/usr/bin/python
#
# Copyright 2011 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""GIT account data model

The relying party account data model.
"""

__author__ = 'Xin Zhou(zhounew@google.com)'

from git.json import git_json

class GitAccount:
  FEDERATED = 'FEDERATED'
  LEGACY = 'LEGACY'
  
  def __init__(self, email, account_type):
    self.email_ = email
    self.account_type_ = GitAccount.LEGACY
    self.local_id_ = ''
    self.display_name_ = ''
    self.photo_url_ = ''
    if account_type == GitAccount.FEDERATED:
      self.account_type_ = GitAccount.FEDERATED
  
  def GetAccountType(self):
    return self.account_type_
  
  def GetEmail(self):
    return self.email_
  
  def SetEmail(self, email):
    self.email_ = email
  
  def SetAccountType(self, account_type):
    if (account_type == GitAccount.FEDERATED or
        account_type == GitAccount.LEGACY):
      self.account_type_ = account_type
  
  def SetLocalId(self, local_id):
    self.local_id_ = local_id
  
  def GetLocalId(self):
    return self.local_id_
  
  def GetDisplayName(self):
    return self.display_name_
  
  def SetDisplayName(self, display_name):
    self.display_name_ = display_name
  
  def GetPhotoUrl(self):
    return self.photo_url_
  
  def SetPhotoUrl(self, photo_url):
    self.photo_url_ = photo_url
  
  def ToJson(self):
    '''Dumps GitAccount into JSON string 
    '''
    obj = {'email':self.email_,
           'displayName':self.display_name_,
           'photoUrl':self.photo_url_,
           'accountType':self.account_type_,
           'localId':self.local_id_}
    return git_json.GitJson().dumps(obj)
  
  @staticmethod
  def FromString(jsonString):
    '''Parses JSON string into GitAccount Object
    '''
    try:
      if not jsonString:
        return None
      obj = git_json.GitJson().loads(jsonString)
      if obj and 'email' in obj and 'accountType' in obj:
        ret = GitAccount(obj['email'], obj['accountType'])
        if 'displayName' in obj:
          ret.SetDisplayName(obj['displayName'])
        if 'photoUrl' in obj:
          ret.SetPhotoUrl(obj['photoUrl'])
        if 'localId' in obj:
          ret.SetLocalId(obj['localId'])
        return ret
      else:
        return None
    except Exception, e:
      return None